using System.Windows.Forms;
using Vin.Event;
using Vin.Extension.Win32.Command.Node;
using Vin.Extension.Win32.Command.Process;
using Vin.Extension.Win32.Command.Workflow;
using Vin.Tool.Attributes;
using Vin.Tool.Core.IntPtrCategory;
using Vin.Tool.Domain.ExceptionModel;
using Vin.Win32.EventArgs;
using Vin.Win32.Input;
using Vin.Win32.Input.Enum;
using Win32;
using Win32.API;

namespace Vin.Extension.Win32.Command.Input;

/// <summary>
/// 获取选中的文本 （模拟按键复制）
/// </summary>
public class SelectedTextNode : BaseNode
{
    public Action? UnRegisterAction { get; set; }

    private string _text = string.Empty;


    public SelectedTextNode()
    {
        UnRegisterAction = VinEventManager.Register<ClipboardUpdateEventArg>(ClipboardUpdate);
    }

    #region 监听剪贴板变化

    private decimal _getTextTime = 500;

    public void ClipboardUpdate(object? sender, VinEventArgs e)
    {
        // 获取剪切板内容
        _text = Clipboard.GetText();
    }

    public async Task GetTextAsync()
    {
        while (string.IsNullOrEmpty(_text))
        {
            if (_getTextTime <= 0)
            {
                throw new BusinessException("获取剪切板内容超时");
            }

            await Task.Delay(100);
            _getTextTime -= 100;
        }
    }

    #endregion

    public override async Task ExecuteAsync(INodeContext context, IWorkflowContext workflowContext)
    {
        if (PrevFocusWindowHandle.IsNullOrZero())
        {
            throw new BusinessException("PrevFocusWindowHandle is null or zero");
        }

        if (User32.IsMaximized(PrevFocusWindowHandle))
        {
            Win32Api.ShowWindow(PrevFocusWindowHandle, Win32Api.SW_SHOW);
        }
        else
        {
            Win32Api.ShowWindow(PrevFocusWindowHandle, Win32Api.SW_SHOWNORMAL);
        }

        if (Win32Api.SetForegroundWindow(PrevFocusWindowHandle))
        {
            // 模拟按键
            VinKeyboardSimulator.Current.KeyPress(VinVirtualKeyCode.CONTROL, VinVirtualKeyCode.VK_C);
            // 获取剪切板内容
            await GetTextAsync();
        }
        else
        {
            throw new BusinessException("SetForegroundWindow failed");
        }

        Console.WriteLine("选定的文本：" + _text);
        workflowContext.WorkflowData.SetResultValue(_text);
    }

    public override void Dispose()
    {
        UnRegisterAction?.Invoke();
    }
}